package com.rrkaige.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Example:
 * Given nums = [2, 7, 11, 15], target = 9,
 * Because nums[0] + nums[1] = 2 + 7 = 9,
 * return [0, 1].
 *
 * @author kaneren
 */
public class A001_TwoSum {
    public static int[] twoSum(int[] numbers, int target) {
        int[] res = new int[2];
        for (int i = 0; i < numbers.length - 1; i++) {
            for (int j = i + 1; j < numbers.length; j++) {
                if (numbers[i] + numbers[j] == target) {
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return res;
    }

    public static int[] twoSum2(int[] numbers, int target) {
        // 数组类似map，(0,2),(1,7),(2,11),(3,15)
        Map<Integer, Integer> map = new HashMap<>();
        // 存放差值和索引，(7,0),(2,1),(-2,2),(-6,3)
        for (int i = 0; i < numbers.length; i++) {
            map.put(target - numbers[i], i);
        }
        for (int i = 0; i < numbers.length; i++) {
            Integer v = map.get(numbers[i]);
            if (v != null && v != i) {
                return new int[]{i, v};
            }
        }
        throw new RuntimeException();
    }

    public static void main(String[] args) {
        int[] numbers = {2, 7, 11, 15};
        int target = 9;
        int[] res = twoSum2(numbers, target);
        System.out.println(Arrays.toString(res));
    }
}
